<template>
    <div class="common-page page-policy-article" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/policy', '/policy/articles', $route.fullPath]"></comp-paths>
            <div class="title" v-if="article">
                <span class="text">{{ article.title }}</span>
                <span class="flag" v-for="tag in article.tags" :key="tag.id">{{ tag.name }}</span>
            </div>
            <div class="title" v-else></div>
        </div>
        <div class="common-page__body common-form" v-if="article">
            <div class="rows">
                <div class="row row--head">
                    <div class="name">基本信息</div>
                    <div class="value">
                        <span class="button button--edit" @click="setArticle()">编辑</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="name">信息标题</div>
                    <div class="value">{{ article.title }}</div>
                </div>
                <div class="row">
                    <div class="name"></div>
                    <div class="value"></div>
                </div>
                <div class="row row--2x">
                    <div class="name">信息摘要</div>
                    <div class="value">{{ article.summary }}</div>
                </div>
                <div class="row">
                    <div class="name">信息正文</div>
                    <div class="value">
                        <span class="button" @click="action('article-content', true)">查看</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">信息来源</div>
                    <div class="value">{{ article.referer }}</div>
                </div>
                <div class="row">
                    <div class="name">信息原文</div>
                    <div class="value">{{ article.source }}</div>
                </div>
                <div class="row">
                    <div class="name">信息作者</div>
                    <div class="value">{{ article.author }}</div>
                </div>
                <div class="row">
                    <div class="name">信息分类</div>
                    <div class="value">
                        <span class="text" v-for="tag in article.tags" :key="tag.id">{{ tag.name }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">申报起止日期</div>
                    <div class="value">{{ article.startAt + " ~ " + article.endAt }}</div>
                </div>
                <div class="row">
                    <div class="name">信息权重</div>
                    <div class="value">{{ article.weight }}</div>
                </div>
                <div class="row">
                    <div class="name">信息浏览量</div>
                    <div class="value">{{ article.views }}</div>
                </div>
            </div>
        </div>
        <div class="common-page__foot" v-if="article">
            <!-- <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="pushArticle()">信息推送</el-button> -->
        </div>
        <comp-dialog title="编辑基本信息" ref="articleSetForm">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="articleSetForm">
                <el-form-item label="信息封面：">
                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px" :src="articleSetForm.banner" v-if="articleSetForm.banner" />
                    <el-button type="plain" icon="el-icon-plus" @click="setArticle('upload-banner')">{{ articleSetForm.banner ? "更换图片" : "选择图片" }}</el-button>
                </el-form-item>
                <el-form-item label="信息标题：" required>
                    <el-input ref="articleSetFormTitle" type="textarea" v-model="articleSetForm.title" style="width: 640px" placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading" @change="setArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息摘要：">
                    <el-input type="textarea" v-model="articleSetForm.summary" style="width: 640px" placeholder="请输入" :maxlength="200" :rows="5" resize="none" :readonly="loading" @change="setArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息正文：">
                    <comp-html-editor ref="articleSetFormContentEditor" style="width: 640px; height: 300px" editing :content="articleSetForm.content"></comp-html-editor>
                </el-form-item>
                <el-form-item label="信息来源：">
                    <el-input v-model="articleSetForm.referer" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息原文：">
                    <el-input v-model="articleSetForm.source" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息作者：">
                    <el-input v-model="articleSetForm.author" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setArticle('validate')"></el-input>
                </el-form-item>
                <el-form-item label="信息分类：">
                    <el-select v-model="articleSetForm.tag.id" style="width: 640px" placeholder="请选择" @change="setArticle('validate')">
                        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="申报日期：">
                    <el-date-picker type="date" v-model="articleSetForm.startTime" style="width: 306px" format="yyyy年M月d日" value-format="timestamp" placeholder="起始日期" :clearable="false" :readonly="loading" @change="addArticle('validate')"></el-date-picker>
                    <span style="margin: 0 0.5em">至</span>
                    <el-date-picker type="date" v-model="articleSetForm.endTime" style="width: 306px" format="yyyy年M月d日" value-format="timestamp" placeholder="截止日期" :clearable="false" :readonly="loading" @change="addArticle('validate')"></el-date-picker>
                </el-form-item>
                <el-form-item label="信息权重：">
                    <el-input v-model="articleSetForm.weight" style="width: 640px" placeholder="请输入" :readonly="loading" @change="setArticle('validate')"></el-input>
                </el-form-item>
                <!-- <el-form-item label="信息状态：">
                    <el-select v-model="articleSetForm.published" style="width: 640px" placeholder="请选择" @change="setArticle('validate')">
                        <el-option v-for="data in env.articlePublisheds" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="setArticle('submit')">保存</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="setArticle('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="信息正文" width="600px" height="80vh" ref="articleContent">
            <comp-html-editor style="height: 100%" ref="articleContentEditor" :content="article.content" v-if="article">
                <template #foot="scope">
                    <el-button type="plain" size="small" icon="el-icon-close" @click="action('article-content', false)">关闭</el-button>
                </template>
            </comp-html-editor>
        </comp-dialog>
        <comp-dialog title="信息推送" width="380px" ref="articlePushForm">
            <el-form size="small" label-width="98px" @submit.native.prevent v-if="articlePushForm">
                <el-form-item label="推送标题：" required>
                    <div style="margin-right: 20px; padding: 5px 0; line-height: 1.5">{{ articlePushForm.title }}</div>
                </el-form-item>
                <el-form-item label="推送用户：">
                    <el-select v-model="articlePushForm.clientRoleToPush" style="width: 160px" placeholder="请选择">
                        <el-option v-for="data in env.userRoles" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="pushArticle('submit')">推送</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="pushArticle('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, deepCopy, toMagicImgURL, selectFile, cache } from "../util";
    export default {
        name: "page-policy-article",
        title: "信息详情",
        nodes: ["/menu/policy"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            articleId: "",
            article: null,
            articleSetForm: null,
            articleContentSetForm: null,
            articlePushForm: null,
            tags: [],
        }),
        methods: {
            action(name, data) {
                if (this.loading) return;
                if (name === "article-content") {
                    if (data) {
                        this.$refs.articleContent.init();
                        this.$nextTick(() => this.$refs.articleContentEditor.init());
                    } else {
                        this.$refs.articleContentEditor.destroy();
                        this.$refs.articleContent.close();
                    }
                }
            },
            setArticle(action, data) {
                if (this.loading) return;
                let form = this.articleSetForm;
                if (!action || action === "start") {
                    this.loading = true;
                    this.plugins.user.getArticleOfTags({ linage: 100, page: 1 }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.tags = res.data.list.reduce((tags, tag) => {
                                let type = this.env.articleTypes.find((type) => type.value === "policy");
                                if (tag.tag.id === type.id) tags.push(tag);
                                return tags;
                            }, []);
                            this.articleSetForm = deepCopy(this.article);
                            this.setArticle("validate");
                            this.$refs.articleSetForm.init();
                            this.$nextTick(() => this.$refs.articleSetFormTitle.focus());
                            this.$nextTick(() => this.$refs.articleSetFormContentEditor.init());
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "validate") {
                    let error = "";
                    form.title = string(form.title).trim();
                    error = error || (form.title ? "" : "请输入信息标题！");
                    form.summary = string(form.summary).trim();
                    form.content = string(() => this.$refs.articleSetFormContentEditor.getContent()) || string(form.content);
                    form.referer = string(form.referer).trim();
                    form.source = string(form.source).trim();
                    form.author = string(form.author).trim();
                    form.editor = string(form.editor).trim();
                    form.startTime = Math.max(int(form.startTime), 0);
                    form.startTime = form.startTime > 0 ? new Date(form.startTime).setHours(0, 0, 0, 0) : null;
                    form.endTime = Math.max(int(form.endTime), 0);
                    form.endTime = form.endTime > 0 ? new Date(form.endTime).setHours(23, 59, 59, 0) : null;
                    form.weight = Math.max(int(form.weight), 0) || null;
                    form.published = form.published || this.env.articlePublisheds[0].value;
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "upload-banner") {
                    if (!data) return selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.setArticle(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "image", progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            form.banner = toMagicImgURL(res.data.value, 120, 120);
                            this.setArticle("validate");
                        } else {
                            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "submit") {
                    if (!this.setArticle("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.setArticle(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.setArticle("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.articleSetForm.close();
                }
            },
            pushArticle(action, data) {
                if (this.loading) return;
                let form = this.articlePushForm;
                if (!action || action === "start") {
                    this.articlePushForm = deepCopy(this.article);
                    this.articlePushForm.clientRoleToPush = this.env.userRoles[0].value;
                    this.$refs.articlePushForm.init();
                } else if (action === "submit") {
                    this.loading = true;
                    this.plugins.user.pushArticle(form.id, form.clientRoleToPush).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("推送成功！", "success");
                            this.pushArticle("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("推送失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.articlePushForm.close();
                }
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                let query = this.$route.query;
                let article = null;
                this.loading = true;
                this.articleId = query.articleId;
                this.article = cache(query.articleId);
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }, async () => {
                    let res = await this.plugins.user.getArticle(query.articleId);
                    if (res.code === 0) article = res.data;
                    return res;
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.article = cache(query.articleId, article);
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/policy/articles"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-policy-article {
        overflow: hidden;
    }
</style>